package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.admin.dto.LoginDto;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-28
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {
    /**
     * 保存自媒体用户
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getApUserId, wmUser.getApUserId());
        int count = this.count(wrapper);
        if (count == 0) {
            this.save(wmUser);
        } else {
            this.updateById(wmUser);
        }
        return ResponseResult.okResult(wmUser);
    }

    /**
     * 自媒体用户登录
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
//        1.登录非空校验
        if (StringUtils.isBlank(loginDto.getName()) || StringUtils.isBlank(loginDto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        2.根据管理员名称查询管理员信息
        LambdaQueryWrapper<WmUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmUser::getName, loginDto.getName());
        WmUser one = this.getOne(wrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        if (one.getStatus() != 9) {
            return ResponseResult.errorResult(400, "账号被锁定，请联系管理员");
        }
//        3.判断密码是否正确
        String pwd = loginDto.getPassword() + one.getSalt();
        String password = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if (!password.equals(one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
//        3.生成令牌，jwt令牌载荷中包含自媒体用户信息
        Map<String, Object> maps = new HashMap<>();
        maps.put("userId", one.getId());
        maps.put("userName", one.getName());
        String token = AppJwtUtil.getToken(maps);
//        4.返回响应业务数据
        HashMap<String, Object> mapResult = new HashMap<>();
//        脱敏处理
        one.setPhone(null);
        one.setSalt(null);
        one.setPassword(null);
//        封装响应数据并返回
        mapResult.put("user", one);
        mapResult.put("token", token);
        return ResponseResult.okResult(mapResult);
    }
}
